package com.chenxin.wms.process.outbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.wms.domain.ObDetailEntity;
import com.chenxin.wms.domain.ObMasterEntity;
import com.chenxin.wms.mapper.ObDetailMapper;
import com.chenxin.wms.mapper.ObMasterMapper;
import com.chenxin.wms.process.outbound.IProcObMasterStatusUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ProcObMasterStatusUpdate implements IProcObMasterStatusUpdate {
    @Autowired
    private ObMasterMapper obMasterMapper;
    @Autowired
    private ObDetailMapper obDetailMapper;

    @Override
    public void statusUpdateByMasterId(Long obMasterId, Long updater) {
// 1.根据主单ID获取对应主单信息
        ObMasterEntity obMaster = obMasterMapper.selectById(obMasterId);
        if (obMaster == null) {
            return;
        }
        // 2.根据主单ID获取对应入库明细单当前最小状态
        QueryWrapper<ObDetailEntity> minStatusUW = new QueryWrapper<>();
        minStatusUW.lambda().eq(ObDetailEntity::getObMasterId, obMasterId)
                .orderByAsc(ObDetailEntity::getObDetailStatus)
                .last("limit 1");

        ObDetailEntity minDetail = obDetailMapper.selectOne(minStatusUW);
        if (minDetail == null) {
            return;
        }
        Integer minStatus = minDetail.getObDetailStatus();
        Date workDate = new Date();
        // 3.将主单状态与明细单最小状态进行同步
        obMaster.setObMasterStatus(minStatus);
        obMaster.setUpdater(updater);
        obMaster.setUpdateDate(workDate);

        obMasterMapper.updateById(obMaster);

        // TODO 根据当前主单状态判断是否需要上报对应系统
    }
}
